﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace print
{
    public partial class main_form : Form
    {
        Config config = new Config("reader");
      public  PatronList readerData = new PatronList("config/patron.xml");
        LabelList labelList =new LabelList("config/Marc.xml");

        RecordList record = new RecordList("config/Marc.xml");
        double bl = 0.254;

       // delegate void drawItem(Graphics g, double x, double y);
        delegate void drawItem(System.Drawing.Printing.PrintPageEventArgs e, double x, double y);
        delegate void drawItem1(System.Drawing.Printing.PrintPageEventArgs e, ref double x, ref double y, out bool new_page);


        public main_form()
        {
           
            InitializeComponent();
            form_init("report");
        }
        private void form_init(string name)
        {
            richTextBox1.Text = "";
            if (name != "card")
            {
                this.txtWidth.Text = config.PageWidth.ToString();
                this.txtHeight.Text = config.PageHeight.ToString();
                this.txtLblHeight.Text = config.ItemHeight.ToString();
                this.txtLblWidth.Text = config.ItemWidth.ToString();
                this.txtItemLeft.Text = config.Left>0? config.Left.ToString():"";
                this.txtItemTop.Text = config.Top>0? config.Top.ToString():"";
                this.txtItemRight.Text = config.Right > 0 ? config.Right.ToString() : "";
                this.txtItemBottom.Text = config.Bottom > 0 ? config.Bottom.ToString() : "";
                this.txtStart.Text = config.Start.ToString();
                this.cmbsort.Text = config.SortBy;


            }
            else
            {
                this.txtWidth.Text = card.PageWidth.ToString();
                this.txtHeight.Text = card.PageHeight.ToString();
                this.txtLblHeight.Text = card.ItemHeight.ToString();
                this.txtLblWidth.Text = card.ItemWidth.ToString();
                this.txtItemLeft.Text = card.Left > 0 ? card.Left.ToString() : "";
                this.txtItemTop.Text = card.Top > 0 ? card.Top.ToString() : "";
            }
            BindAlingSource();
            createItemSource();
            creatLabelDemo();
            setPage(config.PageType, config.PageWidth, config.PageHeight);
            setPosition(name);
            initControl(name);
            //设置纸张
            // pictureBox1.Image = image1;
        }

        private void initControl(string type)
        {

            if (type == "card")
            {
                this.panel1.Hide();
                this.listLbl.Hide();
                this.ckbQiandao.Hide();
                this.ckbBlack.Hide();
                this.txtLabel.Hide();
                this.txtFontSize.Hide();
                this.txtFontFamly.Hide();
                this.listLbl.Hide();
                this.label15.Hide();
                this.label14.Hide();
                this.label13.Hide();
                this.label12.Hide();
                this.label9.Hide();
                this.label8.Hide();
                this.txtcolWidth.Hide();
                this.txtColHeight.Hide();
                this.txtcolTop.Hide();
                this.txtcolLeft.Hide();
                this.txtSplit.Hide();
                this.label6.Hide();
                this.label7.Hide();
                this.cbxAlign.Hide();
                this.cbxisHidden.Hide();
                this.button2.Hide();
                this.label16.Hide();
                txtSplit.Hide();
                label6.Hide();
            }
            else
            {
                this.panel1.Show();
                this.listLbl.Show();
                this.txtHeight.Show();
                this.txtWidth.Show();
                this.ckbQiandao.Show();
                this.ckbBlack.Show();
                this.txtLabel.Show();
                this.txtFontSize.Show();
                this.txtFontFamly.Show();
                this.listLbl.Show();
                this.txtItemTop.Show();
                this.txtLblHeight.Show();
                this.txtItemLeft.Show();
                this.label25.Show();
                this.txtLblWidth.Show();
                this.label15.Show();
                this.label14.Show();
                this.label13.Show();
                this.label12.Show();
                this.label9.Show();
                this.label8.Show();
                this.txtcolWidth.Show();
                this.txtColHeight.Show();
                this.txtcolTop.Show();
                this.txtcolLeft.Show();
                this.txtSplit.Show();
                this.label6.Show();
                this.label7.Show();
                this.cbxAlign.Show();
                this.cbxisHidden.Show();
                this.button2.Show();
                this.label16.Show();
            }


            ckbQiandao.Hide();
            button3.Hide();
            cbxisHidden.Hide();
            pbhuibiao.Hide();
            label10.Hide();
            button4.Hide();
            ckbchektype.Hide();
            txtLabel.Hide();
            label16.Hide();

            label6.Hide();
            txtSplit.Hide();
            label27.Hide();
            txtStart.Hide();
            label28.Hide();
            cmbsort.Hide();

        
            if (type == "reader")
            {
                button3.Show();
                cbxisHidden.Show();
                pbhuibiao.Show();
                label10.Show();
                button4.Show();
                ckbchektype.Show();
                txtLabel.Show();
                label16.Show();
               // label6.Show();
               // txtSplit.Show();
            }

            else if (type == "report")
            {
                txtLabel.Show();
                label16.Show();
                label6.Show();
                txtSplit.Show();
            }
            else if (type == "label")
            {
                label6.Show();
                txtSplit.Show();
                label27.Show();
                txtStart.Show();
                label28.Show();
                cmbsort.Show();
            }
            //else if(type == "card")
            //{
            //    label6.Show();
            //    txtSplit.Show();
            //}
        }

        private void setPosition(string type)
        {
            if (type!="report")
            {
                this.panel1.Location = new System.Drawing.Point(299, 117);
                this.listLbl.Size = new System.Drawing.Size(120, 100);
                this.txtHeight.Location = new System.Drawing.Point(327, 12);
                this.txtWidth.Location = new System.Drawing.Point(238, 12);
                this.ckbQiandao.Location = new System.Drawing.Point(102, 287);
                this.ckbBlack.Location = new System.Drawing.Point(102, 254);
                this.txtLabel.Location = new System.Drawing.Point(53, 422);
                this.txtFontSize.Location = new System.Drawing.Point(58, 251);
                this.txtFontFamly.Location = new System.Drawing.Point(58, 224);
                this.listLbl.Location = new System.Drawing.Point(18, 101);
                this.txtItemTop.Location = new System.Drawing.Point(411, 17);
                this.txtLblHeight.Location = new System.Drawing.Point(179, 17);
                this.txtItemLeft.Location = new System.Drawing.Point(299, 17);
                this.label25.Location = new System.Drawing.Point(358, 20);
                this.txtLblWidth.Location = new System.Drawing.Point(67, 17);
                this.label15.Location = new System.Drawing.Point(5, 400);
                this.label14.Location = new System.Drawing.Point(5, 376);
                this.label13.Location = new System.Drawing.Point(16, 349);
                this.label12.Location = new System.Drawing.Point(16, 319);
                this.label9.Location = new System.Drawing.Point(16, 264);
                this.label8.Location = new System.Drawing.Point(16, 233);
                this.txtcolWidth.Location = new System.Drawing.Point(53, 315);
                this.txtColHeight.Location = new System.Drawing.Point(53, 344);
                this.txtcolTop.Location = new System.Drawing.Point(54, 371);
                this.txtcolLeft.Location = new System.Drawing.Point(55, 396);
                this.txtSplit.Location = new System.Drawing.Point(55, 452);
                this.label6.Location = new System.Drawing.Point(10, 452);
                this.label7.Location = new System.Drawing.Point(16, 289);
                this.cbxAlign.Location = new System.Drawing.Point(53, 285);
                this.cbxisHidden.Location = new System.Drawing.Point(18, 479);
                this.button2.Location = new System.Drawing.Point(122, 224);
                this.label16.Location = new System.Drawing.Point(5, 422);
            }
            else
            {
                this.panel1.Location = new System.Drawing.Point(21, 96);
                this.listLbl.Size = new System.Drawing.Size(120, 208);

                this.txtHeight.Location = new System.Drawing.Point(327, 12);
                this.txtWidth.Location = new System.Drawing.Point(238, 12);
                this.cbxisHidden.Location = new System.Drawing.Point(436, 357);
                this.cbxAlign.Size = new System.Drawing.Size(43, 20);
                this.txtSplit.Location = new System.Drawing.Point(349, 353);
                this.txtcolLeft.Location = new System.Drawing.Point(399, 326);
                this.txtcolTop.Location = new System.Drawing.Point(398, 301);
                this.txtColHeight.Location = new System.Drawing.Point(397, 274);
                this.txtcolWidth.Location = new System.Drawing.Point(397, 245);
                this.ckbQiandao.Location = new System.Drawing.Point(271, 316);
                this.ckbBlack.Location = new System.Drawing.Point(271, 283);
                this.txtLabel.Location = new System.Drawing.Point(222, 352);
                this.txtFontSize.Location = new System.Drawing.Point(227, 280);
                this.txtFontFamly.Location = new System.Drawing.Point(227, 253);
                this.listLbl.Location = new System.Drawing.Point(18, 241);
                this.txtItemTop.Location = new System.Drawing.Point(411, 17);
                this.txtLblHeight.Location = new System.Drawing.Point(179, 17);
                this.txtItemLeft.Location = new System.Drawing.Point(299, 17);
                this.label6.Location = new System.Drawing.Point(287, 355);
                this.label15.Location = new System.Drawing.Point(347, 331);
                this.label14.Location = new System.Drawing.Point(347, 307);
                this.label13.Location = new System.Drawing.Point(358, 280);
                this.label12.Location = new System.Drawing.Point(358, 250);
                this.label7.Location = new System.Drawing.Point(185, 318);
                this.label9.Location = new System.Drawing.Point(185, 293);
                this.label8.Location = new System.Drawing.Point(185, 262);
                this.cbxAlign.Location = new System.Drawing.Point(222, 314);
                this.label16.Location = new System.Drawing.Point(185, 352);

                this.button2.Location = new System.Drawing.Point(292, 250);


            }
        }
        C_Code128 c_Code128 = new C_Code128();

       
        int _curPageIndex = 0;
        private int _pageSize = 0;
        private int _pageIndex = 0;
        private int _totalPage;

        private int _fromPage = 0;
        private int _toPage = 1;


        int _colCount = 1;
        int _rowCount = 1;


        //每页打印的记录条数  

        private void initPrint()
        {

            int width = 0;
            int height = 0;
            if (printTypeView.SelectedNode.Text == "标签打印")
            {
                initLabelPrint();
                 width = (int)Math.Round(config.PageWidth / bl);
                 height = (int)Math.Round(config.PageHeight / bl);
            }
            else if (printTypeView.SelectedNode.Text == "读者证打印")
            {
                initReaderPrint();
                width = (int)Math.Round(config.PageWidth / bl);
                height = (int)Math.Round(config.PageHeight / bl);
            }
            else if (printTypeView.SelectedNode.Text == "财产帐报表")
            {
                initReportPrint();
                width = (int)Math.Round(config.PageWidth / bl);
                height = (int)Math.Round(config.PageHeight / bl);
            }
            else if (printTypeView.SelectedNode.Text == "卡片打印")
            {
                initCardPrint();
                width = (int)Math.Round(card.PageWidth / bl);
                height = (int)Math.Round(card.PageHeight / bl);
            }

            PaperSize p = new PaperSize("Custom",width, height);

            this.printDocument.DefaultPageSettings.PaperSize = p;
         

        }

        public void createItemSource()
        {
           // listLbl.SelectedValue = "";
            DataTable dt = new DataTable();
            dt.Columns.Add("Text", Type.GetType("System.String"));
            dt.Columns.Add("Value", Type.GetType("System.String"));


            foreach (KeyValuePair<string, SettingItem> item in config.Settings)
            {
                var row = item.Value;

                string label =string.IsNullOrEmpty( row.Label)? row.Name : row.Label;
                dt.Rows.Add(label, row.Name+row.Label);
            }
            
            listLbl.DataSource = dt;
            listLbl.DisplayMember = "Text";   // Text，即显式的文本
            listLbl.ValueMember = "Value";    // Value，即实际的值
            listLbl.SelectedIndex = 0;        //  设置为默认选中第一个

        }

        public void BindAlingSource()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Text", Type.GetType("System.String"));
            dt.Columns.Add("Value", Type.GetType("System.String"));

   
            dt.Rows.Add("左", "left");
            dt.Rows.Add("中", "center");
            dt.Rows.Add("右", "right");

            cbxAlign.DataSource = dt;
            cbxAlign.DisplayMember = "Text";   // Text，即显式的文本
            cbxAlign.ValueMember = "Value";    // Value，即实际的值
            cbxAlign.SelectedIndex = 0;        //  设置为默认选中第一个
        }
        private int _printType = 0;
        private void initReaderPrint()
        {
            readerData = new PatronList("config/patron.xml");
            if (richTextBox1.Text.Length > 0)
            {
               
                string[] ids = richTextBox1.Text.Split(' ', ',', '\n');

               List<Patron> list = readerData.List.FindAll(item =>
                {
                    if (item != null)
                    {
                        return ids.Contains(item.Idcardno.ToUpper());

                    }
                    else
                    {
                        return false;
                    }
                });

                readerData.List = list;

            }
            this._colCount = (int)Math.Floor((double)((config.PageWidth - config.Left - config.Right) / config.ItemWidth));
            this._rowCount = (int)Math.Floor((double)((config.PageHeight - config.Top - config.Bottom) / config.ItemHeight));
            if (ckbchektype.SelectedIndex > -1)
            {
                _printType = ckbchektype.SelectedIndex;
            }
            this._pageSize = this._colCount * this._rowCount;
            if (this._pageSize == 0)
            {
                this._pageSize = 1;
            }
            this._curPageIndex = 0;
            this._totalPage =Convert.ToInt32( Math.Ceiling((double) (readerData.List .Count/ _pageSize)));
        }
        private void initLabelPrint()
        {
             labelList = new LabelList("config/Marc.xml");

            List<LabelItem> list = new List<LabelItem>();
            if (richTextBox1.Text.Length > 0)
            {
                string[] ids = richTextBox1.Text.Split(' ', ',', '\n');

                list = labelList.List.FindAll(item =>
                {
                    if (item != null)
                    {
                        return ids.Contains(item.getKey("b").ToUpper());
                    }
                    else
                    {
                        return false;
                    }
                });

                labelList.List = list;

            }
            if (config.SortBy != "")
            {
                labelList.List.Sort((cur, next) =>
                {

                if (cur!=null&&next!=null&&config.SortBy == "905b")
                {

                    return int.Parse(Regex.Replace(cur.getKey(config.SortBy.Replace("905", "")), "[^0-9]", "")).CompareTo(int.Parse(Regex.Replace(next.getKey(config.SortBy.Replace("905", "")), "[^0-9]", "")));
                }
              
                else if (cur != null && next != null && config.SortBy == "905w") {
                    return DateTime.Parse(cur.getKey(config.SortBy.Replace("905", ""))).CompareTo(DateTime.Parse(next.getKey(config.SortBy.Replace("905", ""))));
            }
            else
            {
                return config.SortD == "1" ? 1 : 0;
            }
                });
            }
            if (config.Start>0)
            {
                for(int i = 0; i < config.Start; i++)
                {
                   // LabelItem item = new LabelItem();
                    labelList.List.Insert(0, null);
                }
            }


            this._colCount = (int)Math.Floor((double)((config.PageWidth - config.Left - config.Right) / config.ItemWidth));
            this._rowCount = (int)Math.Floor((double)((config.PageHeight - config.Top - config.Bottom) / config.ItemHeight));
            this._pageSize = this._colCount * this._rowCount;
            this._curPageIndex = 0;
            this._totalPage = Convert.ToInt32(Math.Ceiling(((double)labelList.List.Count / _pageSize)));
        }

        List<Record> reportRecord = new List<Record>();

       
        private void initReportPrint()
        {

            reportRecord = new List<Record>();

            if (config.GroupBy=="0") {
                record.ForEach(re =>
                {
                    var list905 = re.Datafield["905"];

                    if (list905.GetType().Name.Contains("List"))
                    {
                        List<Dictionary<string, string>> temp = (List<Dictionary<string, string>>)list905;
                        string b = "";
                        double p = 0;
                        Record r1 = new Record() { Controlfield = re.Controlfield, Datafield=re.Datafield };

                        temp.ForEach(item11 =>
                        {

                            b += item11["b"]+",";
                            p += double.Parse(item11["p"]);
                           
                        });
                        temp[0]["b"] = b;
                        temp[0]["p"] = p.ToString("F2");

                        r1.Datafield["905"] = temp[0];
                        //re.Datafield.Keys.ToList<string>().ForEach(key =>
                        //{
                        //    if (key != "905")
                        //    {
                        //        r1.Datafield[key] = re.Datafield[key];
                        //    }
                        //    else
                        //    {
                        //        r1.Datafield[key] = item11;
                        //    }
                        //});
                        //r1.Datafield["905"] = item11;
                        reportRecord.Add(r1);

                    }
                    else
                    {
                        reportRecord.Add(re);
                    }
                });

            }
            else
            {
                record.ForEach(re =>
                {
                    var list905 = re.Datafield["905"];

                    if (list905.GetType().Name.Contains("List"))
                    {
                        List<Dictionary<string, string>> temp = (List<Dictionary<string, string>>)list905;
                        temp.ForEach(item11 =>
                        {
                            Record r1 = new Record() { Controlfield = re.Controlfield };

                            re.Datafield.Keys.ToList<string>().ForEach(key =>
                            {
                                if (key != "905")
                                {
                                    r1.Datafield[key] = re.Datafield[key];
                                }
                                else
                                {
                                    r1.Datafield[key] = item11;
                                }
                            });
                            r1.Datafield["905"] = item11;
                            reportRecord.Add(r1);
                        });
                    }
                    else
                    {
                        reportRecord.Add(re);
                    }
                });
            }

            this._colCount = 1; //(int)Math.Floor((double)((config.PageWidth - config.Left) / config.ItemWidth));
             this._rowCount = (int)Math.Floor((double)((config.PageHeight - config.Top*2) / config.ItemHeight));
            this._pageSize = this._colCount * this._rowCount;
            this._curPageIndex = 0;
            this._totalPage = Convert.ToInt32(Math.Ceiling((double)((reportRecord.Count+1) / _pageSize)));
        }

        private void initCardPrint()
        {
            this._colCount = 1;// (int)Math.Floor((double)((config.PageWidth - config.Left) / config.ItemWidth));
            this._rowCount = 1;// (int)Math.Floor((double)((config.PageHeight - config.Top) / config.ItemHeight));
            this._pageSize = 1;// this._colCount * this._rowCount;
            this._curPageIndex = 0;
            this._totalPage = 1; // Convert.ToInt32(Math.Ceiling((double)(readerData.List.Count / _pageSize)));
            setPage("", Convert.ToInt32(card.ItemWidth),Convert.ToInt32( card.ItemHeight));
            this._cardPagelist = null;
        }

        private void printDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
           // this.printDocument.DocumentName = "10";  //设置打印总页数
            createPrint(e);
        }


        private void createPrint(System.Drawing.Printing.PrintPageEventArgs e)
        {
            if (printTypeView.SelectedNode.Text == "标签打印")
            {
                //creatLabel(e);
                drawPage(e, new drawItem(drawLabel));


            }
            else if (printTypeView.SelectedNode.Text == "读者证打印")
            {
                //creatReader(e);
                drawPage1(e,new drawItem(drawReader));
            }
           else if (printTypeView.SelectedNode.Text == "财产帐报表")
            {
                // creatReport(e);
                creatReportHeader(e);
                drawPageReport(e, new drawItem1(drawReport));

            }
            else if (printTypeView.SelectedNode.Text == "卡片打印")
            {
                drawCard(e);

                   //drawPage(e, new drawItem(drawCard));
            }
        }

        private void creatReportHeader(System.Drawing.Printing.PrintPageEventArgs e)
        {
            Graphics g = e.Graphics;
            Font f = new Font("黑体", 18);
            SolidBrush s = new SolidBrush(Color.Black);

            StringFormat format = new StringFormat();

            Pen pen = new Pen(Color.Black);
            int _c = 0;
            int left = 0;
            foreach (KeyValuePair<string, SettingItem> item in config.Settings)
            {

                var row = item.Value;

                format.Alignment = StringAlignment.Center; // getTextAlign(row.Align);
                double x =Math.Ceiling( config.Left / bl);
                double y = Math.Ceiling(config.Top / bl);
                string text =row.Label;


                //if (_c == 0)
                //{
                //    //  左边线
                //    g.DrawLine(pen, (int)x + (int)Math.Ceiling((row.Left) / bl), (int)y, (int)x + (int)Math.Ceiling((row.Left) / bl), (int)y + (int)Math.Ceiling((row.Top + row.Height) / bl));
                //}
                ////上边线
                //g.DrawLine(pen, (int)x + (int)Math.Ceiling(row.Left / bl),
                //    (int)y,
                //    (int)x + (float)Math.Ceiling((row.Left + row.Width) / bl),
                //    (int)y);
                ////右边线
                //g.DrawLine(pen, (int)x + (int)Math.Ceiling((row.Left + row.Width) / bl),
                //    (int)y, (int)x + (int)Math.Ceiling((row.Left + row.Width) / bl),
                //    (int)y + (int)Math.Ceiling((row.Top + row.Height) / bl));
                ////下边线
                //g.DrawLine(pen,
                //    (int)x + (int)Math.Ceiling((row.Left) / bl),
                //    (int)y + (int)Math.Ceiling((row.Height) / bl),
                //    (int)x + (int)Math.Ceiling((row.Left + row.Width) / bl),
                //    (int)y + (int)Math.Ceiling((row.Height) / bl));


                Rectangle rect = new Rectangle((int)x+ left,
                    (int)y , (int)Math.Ceiling(row.Width / bl),
                    (int)Math.Ceiling(row.Height / bl));
                format.LineAlignment = StringAlignment.Center;
               g.DrawRectangle(pen, (int)x + left, (int)y, (int)Math.Ceiling(row.Width / bl), (int)Math.Ceiling(row.Height / bl));
                f = new Font(row.FontFamly, int.Parse(row.FontSize), row.Black ? FontStyle.Bold : FontStyle.Regular);
                s = new SolidBrush(row.Color);
                g.DrawString(text, f, s, rect, format);//需要的参数
                left += (int)Math.Ceiling(row.Width / bl);
                _c++;
            }
        }



        private  void drawPage(System.Drawing.Printing.PrintPageEventArgs e, drawItem drawItem)
        {
            Graphics g = e.Graphics;
            Font f = new Font("黑体", 18);
            SolidBrush s = new SolidBrush(Color.Black);
            Pen pen = new Pen(Color.Black);

            double w = Math.Ceiling(config.ItemWidth / bl);
            double h = Math.Ceiling(config.ItemHeight / bl);
            StringFormat format = new StringFormat();
            //  format.LineAlignment = StringAlignment.Center;
            format.Alignment = StringAlignment.Far; //居中

            if (this._fromPage > -1)
            {
                this._pageIndex++;
                e.HasMorePages = true;
            }

          
            int i = 0;
            int j = 0;
            //double x =Math.Ceiling( config.Left / bl) ;
            //double y = Math.Ceiling(config.Top / bl) ;
            while (this._curPageIndex < this._pageSize * (this._pageIndex + 1) && this._curPageIndex < labelList.List.Count)
            {
                LabelItem data = labelList.List[this._curPageIndex];
                double x = config.Left / bl + j * w;
                double y = config.Top / bl + i * h;
                // g.DrawRectangle(pen, (float)x, (float)y, (float)w, (float)h);
                drawItem(e, x, y);
               
                if (j >= 0 && j == this._colCount - 1)
                {
                    j = 0;
                    if (i < this._rowCount - 1)
                    {
                        i++;
                    }
                }
                else
                {
                    j++;
                }
                this._curPageIndex++;

                // e.HasMorePages = false;
            }
            if (this._pageIndex+1 < this._totalPage)
            {
                this._pageIndex++;
                e.HasMorePages = true;
                printPreviewControl.Rows++;
            }
            else
            {
                e.HasMorePages = false;
            }
            if (this._toPage>-1&&this._toPage <= this._pageIndex)
            {
                e.HasMorePages = false;

            }
        }


        private void drawPageReport(System.Drawing.Printing.PrintPageEventArgs e, drawItem1 drawItem)
        {
            Graphics g = e.Graphics;
            Font f = new Font("黑体", 18);
            SolidBrush s = new SolidBrush(Color.Black);
            Pen pen = new Pen(Color.Black);

            double w = Math.Ceiling(config.ItemWidth / bl);
            double h = Math.Ceiling(config.ItemHeight / bl);
            StringFormat format = new StringFormat();
            //  format.LineAlignment = StringAlignment.Center;
            format.Alignment = StringAlignment.Far; //居中


            int i = 0;
            int j = 0;
            double x = Math.Ceiling(config.Left / bl);
            double y = Math.Ceiling(config.Top / bl);
            //while (this._curPageIndex < this._pageSize * (this._pageIndex + 1) && this._curPageIndex < reportRecord.Count)

                while ( this._curPageIndex < reportRecord.Count)
            {
                bool new_page = false;
                drawItem(e, ref x, ref y,out new_page);
                x += j * w;

                if (new_page)
                {
                   // this._curPageIndex++;
                    y = Math.Ceiling(config.Top / bl);
                    e.HasMorePages = true;
                    printPreviewControl.Rows++;
                    break;
                }
               // y += h;

                this._curPageIndex++;

                // e.HasMorePages = false;
            }
            if (this._curPageIndex < this.reportRecord.Count)
            {
                e.HasMorePages = true;
                printPreviewControl.Rows++;
            }
            else
            {
                e.HasMorePages = false;
            }
        }


        List<Dictionary<string, object>> pageReadf = new List<Dictionary<string, object>>();

        private void drawPage1(System.Drawing.Printing.PrintPageEventArgs e, drawItem drawItem)
        {
            Graphics g = e.Graphics;
            Font f = new Font("黑体", 18);
            SolidBrush s = new SolidBrush(Color.Black);
            Pen pen = new Pen(Color.Black);

            double w = config.ItemWidth / 0.254;
            double h = config.ItemHeight / 0.254;
            StringFormat format = new StringFormat();
            //  format.LineAlignment = StringAlignment.Center;
            format.Alignment = StringAlignment.Far; //居中

            int i = 0;
            int j = 0;
            int tempindex = this._curPageIndex;
            if (pageReadf != null && pageReadf.Count > 0)
            {
                pageReadf.ForEach(item =>
                {
                    e.Graphics.DrawString(item["text"].ToString(), (Font)(item["f"]), (SolidBrush)item["s"], (Rectangle)item["rect"], (StringFormat)item["format"]);
                });

                pageReadf = null;
                if (this._pageIndex < this._totalPage)
                {
                    this._pageIndex++;
                    e.HasMorePages = true;
                    printPreviewControl.Rows++;
                }
                else
                {
                    e.HasMorePages = false;
                }
            }
            else
            {
                pageReadf = new List<Dictionary<string, object>>();

                while (this._curPageIndex < this._pageSize * (this._pageIndex + 1) && this._curPageIndex < readerData.List.Count)
                {
                    double x = config.Left / bl + j * w;
                    double y = config.Top / bl + i * h;
                    if (_printType == 2)
                    {
                        drawItem(e, x, y);
                        pageReadf.Add(drawReaderf(e, x, y));
                    }
                    else if (_printType == 1)
                    {
                        Dictionary<string, object> item = drawReaderf(e, x, y);
                      
                            e.Graphics.DrawString(item["text"].ToString(), (Font)(item["f"]), (SolidBrush)item["s"], (Rectangle)item["rect"], (StringFormat)item["format"]);
                      

                    }
                    else if (_printType == 0)
                    {
                        drawItem(e, x, y);
                    }
                    if (j >= 0 && j == this._colCount - 1)
                    {
                        j = 0;
                        if (i < this._rowCount - 1)
                        {
                            i++;
                        }
                    }
                    else
                    {
                        j++;
                    }
                    this._curPageIndex++;
                }
                if (_printType == 1)
                {
                    if (this._curPageIndex < readerData.List.Count)
                    {
                        this._pageIndex++;
                        printPreviewControl.Rows++;
                        e.HasMorePages = true;
                    }
                }
               else if (_printType == 2)
                {
                    printPreviewControl.Rows++;
                    e.HasMorePages = true;
                }
                else
                {
                    if (this._curPageIndex < readerData.List.Count)
                    {
                        this._pageIndex++;

                        printPreviewControl.Rows++;
                        e.HasMorePages = true;
                    }
                }
            }
        }



        private void drawReader(System.Drawing.Printing.PrintPageEventArgs e, double x, double y)
        {
            Graphics g = e.Graphics;
            
            StringFormat format = new StringFormat();
            Font f = new Font("黑体", 18);
            SolidBrush s = new SolidBrush(Color.Black);
           if(readerData.List.Count<=_curPageIndex)
            {
                return;
            }
            Patron data = readerData.List[this._curPageIndex];
          
            foreach (KeyValuePair<string, SettingItem> item in config.Settings)
            {
                var row = item.Value;
                if (row.IsHide)
                {
                    continue;
                }
                format.Alignment = getTextAlign(row.Align);

               
                if (row.Name == "img")
                {
                    string imgpath = label10.Text != ""? label10.Text : "config/images";
                    
                    if (File.Exists(imgpath + "/" + data.Idcardno + ".jpg"))
                    {
                        Image imageHead = Image.FromFile(imgpath+"/" + data.Idcardno + ".jpg");

                        if (imageHead != null)
                        {
                            g.DrawImage(imageHead, (int)x + (int)Math.Floor(row.Left / bl), (int)y + (int)Math.Floor(row.Top / bl), (int)Math.Floor(row.Width / bl), (int)Math.Floor(row.Height / bl));

                        }
                    }
                }
               else if (row.Name == "huibiao")
                {
                    if (pbhuibiao.Image != null)
                    {
                        g.DrawImage(pbhuibiao.Image, (int)x + (int)Math.Floor(row.Left / bl), (int)y + (int)Math.Floor(row.Top / bl), (int)Math.Floor(row.Width / bl), (int)Math.Floor(row.Height / bl));

                    }
                }
                else if (row.Name.Trim() == "BARCODE")
                {
                    string text = row.Label;
                    f = new Font(row.FontFamly, int.Parse(row.FontSize), row.Black ? FontStyle.Bold : FontStyle.Regular);
                    s = new SolidBrush(row.Color);
                    Rectangle rect = new Rectangle((int)x + (int)Math.Floor(row.Left / bl), (int)y + (int)Math.Floor((row.Top) / bl), (int)Math.Floor(row.Width / bl), (int)Math.Floor(row.Height / bl));
                    format.LineAlignment = StringAlignment.Center;
                    g.DrawString(text, f, s, rect, format);//需要的参数

                    SizeF sizeF = g.MeasureString(text, f, 500, format);
                    Image imageCode = c_Code128.GetCodeImage(data.getKey(row.Name), C_Code128.Encode.Code128B);


                    string text_cont = data.getKey(row.Name);
                    format.Alignment = StringAlignment.Center;
                    SettingItem content = row.Content[0];
                    Font f1 = new Font(content.FontFamly, int.Parse(content.FontSize));
                    s = new SolidBrush(row.Color);
                    SizeF sizeF1 = g.MeasureString(text_cont, f1, 500, format);

                    if (imageCode != null)
                    {
                        g.DrawImage(imageCode, (int)x + (int)Math.Floor(row.Left / bl) + sizeF.Width, (int)y + (int)Math.Floor(row.Top / bl), (int)Math.Floor(row.Width / bl) - sizeF.Width, (int)Math.Floor((row.Height) / bl - sizeF1.Height));
                    }

                    rect = new Rectangle((int)x + (int)Math.Floor(row.Left / bl) + (int)sizeF.Width, (int)y + (int)Math.Floor((row.Top + row.Height) / bl - sizeF1.Height), (int)Math.Floor(row.Width / bl) - (int)sizeF.Width, (int)Math.Floor(sizeF1.Height));


                    //g.DrawRectangle(pen, (float)x + (float)Math.Floor(row.Left / bl), (float)y + (float)Math.Floor(row.Top / bl), (float)(int)Math.Floor(row.Width / bl), (float)(int)Math.Floor(row.Height / bl));
                    g.DrawString(text_cont, f1, s, rect, format);//需要的参数

                }
                else
                {
                    if (row.Label == "反面")
                    {
                        continue;
                    }
                    string text = row.Label;
                    s = new SolidBrush(row.Color);
                    Rectangle rect = new Rectangle((int)x + (int)Math.Floor(row.Left / bl), (int)y + (int)Math.Floor(row.Top / bl), (int)Math.Floor(row.Width / bl), (int)Math.Floor(row.Height / bl));
                    f = new Font(row.FontFamly, int.Parse(row.FontSize), row.Black ? FontStyle.Bold : FontStyle.Regular);
                    s = new SolidBrush(row.Color);
                    g.DrawString(text, f, s, rect, format);//需要的参数
                    SizeF sizeF = g.MeasureString(text, f, 500, format);

                    if (row.Content != null && row.Content.Count > 0)
                    {
                        SettingItem content = row.Content[0];

                        text = data.getKey(row.Name);
                        if (row.Map != null && row.Map.ContainsKey(data.getKey(row.Name)))
                        {
                            text = row.Map[data.getKey(row.Name)];

                        }
                        s = new SolidBrush(content.Color);

                        rect = new Rectangle((int)x + (int)Math.Floor((row.Left + content.Left) / bl) + (int)sizeF.Width, (int)y + (int)Math.Floor((row.Top + content.Top) / bl), (int)Math.Floor(row.Width / bl), (int)Math.Floor(row.Height / bl));
                        f = new Font(row.FontFamly, int.Parse(row.FontSize), row.Black ? FontStyle.Bold : FontStyle.Regular);
                        s = new SolidBrush(row.Color);
                        //g.DrawRectangle(pen, (float)x + (float)Math.Floor(row.Left / bl), (float)y + (float)Math.Floor(row.Top / bl), (float)(int)Math.Floor(row.Width / bl), (float)(int)Math.Floor(row.Height / bl));
                        g.DrawString(text, f, s, rect, format);//需要的参数;
                    }

                }
            }

           
        }


        private Dictionary<string, object> drawReaderf(System.Drawing.Printing.PrintPageEventArgs e, double x, double y)
        {
            Graphics g = e.Graphics;

            StringFormat format = new StringFormat();
           
            var row = config.Settings["反面反面"];
            string text = row.ItemContent;
            Font f = new Font(row.FontFamly,Convert.ToInt32( row.FontSize));
            SolidBrush s = new SolidBrush(row.Color);
            Rectangle rect = new Rectangle((int)x + (int)Math.Floor(row.Left / bl), (int)y + (int)Math.Floor(row.Top / bl), (int)Math.Floor(row.Width / bl), (int)Math.Floor(row.Height / bl));
            f = new Font(row.FontFamly, int.Parse(row.FontSize), row.Black ? FontStyle.Bold : FontStyle.Regular);
            s = new SolidBrush(row.Color);
            Dictionary<string, object> drawp = new Dictionary<string, object>();

            drawp.Add("text", text);
            drawp.Add("f", f);
            drawp.Add("s", s);
            drawp.Add("format", format);
           


            drawp.Add("rect", rect);

            return drawp;
        }


        private void drawLabel(System.Drawing.Printing.PrintPageEventArgs evt, double x, double y)
        {
            Graphics g = evt.Graphics;

            Font f = new Font("黑体", 18);
            SolidBrush s = new SolidBrush(Color.Black);

            StringFormat format = new StringFormat();


            LabelItem data = this.labelList.List[this._curPageIndex];

            if (data == null)
            {
                return;
            }

            format.LineAlignment = StringAlignment.Center;

            SettingItem d = config.Settings["905d"];
            SettingItem e = config.Settings["905e"];
            SettingItem b = config.Settings["905b"];

            if (d.Top == e.Top)  //说明905d和905e在一行
            {
                SettingItem row = d;
                format.Alignment = getTextAlign(row.Align);

                string text = data.getKey(row.Name.Replace("905", ""));
               
                text += row.Split;
                string text1= data.getKey(e.Name.Replace("905", ""));
                int out_i = 0;
                if (!e.Qiandao && int.TryParse(text1, out out_i))
                {
                    text1 = out_i.ToString();
                }
                text += text1;

                Rectangle rect = new Rectangle((int)x + (int)Math.Floor(row.Left / bl), (int)y + (int)Math.Floor(row.Top / bl), (int)Math.Floor(row.Width / bl), (int)Math.Floor(row.Height / bl));
                f = new Font(row.FontFamly, int.Parse(row.FontSize), row.Black ? FontStyle.Bold : FontStyle.Regular);
                g.DrawString(text, f, s, rect, format);//需要的参数

                row = b;

                format.Alignment = getTextAlign(row.Align);

                text = data.getKey(row.Name.Replace("905", ""));

                rect = new Rectangle((int)x + (int)Math.Floor(row.Left / bl), (int)y + (int)Math.Floor(row.Top / bl), (int)Math.Floor(row.Width / bl), (int)Math.Floor(row.Height / bl));
                f = new Font(row.FontFamly, int.Parse(row.FontSize), row.Black ? FontStyle.Bold : FontStyle.Regular);
                g.DrawString(text, f, s, rect, format);//需要的参数
            }
            else
            {
                foreach (KeyValuePair<string, SettingItem> item in config.Settings)
                {
                    var row = item.Value;
                    format.Alignment = getTextAlign(row.Align);

                    string text = data.getKey(row.Name.Replace("905", ""));
                    int out_i = 0;
                    if (!row.Qiandao && int.TryParse(text, out out_i))
                    {
                        text = out_i.ToString();
                    }
                    text += row.Split;
                    Rectangle rect = new Rectangle((int)x + (int)Math.Floor(row.Left / bl), (int)y + (int)Math.Floor(row.Top / bl), (int)Math.Floor(row.Width / bl), (int)Math.Floor(row.Height / bl));
                    f = new Font(row.FontFamly, int.Parse(row.FontSize), row.Black ? FontStyle.Bold : FontStyle.Regular);
                    g.DrawString(text, f, s, rect, format);//需要的参数
                }
            }

          
        }
        string drawtype = "0";
        private void drawReport(System.Drawing.Printing.PrintPageEventArgs evt, ref double x, ref double y,out bool new_page)
        {
            Graphics g = evt.Graphics;
            new_page = false;
            Font f = new Font("黑体", 18);
            SolidBrush s = new SolidBrush(Color.Black);

            StringFormat format = new StringFormat();

            if (this._curPageIndex >= reportRecord.Count)
            {
                return;
            }
            Record data = reportRecord[this._curPageIndex];


            Pen pen = new Pen(Color.Black);
            int _c = 0;
            float relheight = 0;
            foreach (KeyValuePair<string, SettingItem> item in config.Settings)
            {
                var row = item.Value;

                format.Alignment = getTextAlign(row.Align);
                format.LineAlignment = StringAlignment.Center;
                string text = ""; //row.Label;
                string[] names = row.Name.Split('/');

                for (int i = 0; i < names.Length; i++)
                {

                    if (data.Datafield.ContainsKey(names[i]))
                    {
                        var val = data.Datafield[names[i]];
                        for (int j = 0; j < row.Content.Count; j++)
                        {

                            //val[row.Content[j].Name];
                            if (val.GetType().Name.Contains("List"))
                            {
                                List<Dictionary<string, string>> temp = (List<Dictionary<string, string>>)val;
                                text += temp[0][row.Content[j].Name];// data.Datafield.getKey(row.Name);

                            }
                            else
                            {
                                Dictionary<string, string> temp = (Dictionary<string, string>)val;
                                if (temp.ContainsKey(row.Content[j].Name))
                                {

                                    text += temp[row.Content[j].Name];// data.Datafield.getKey(row.Name);

                                }
                            }

                        }
                    }
                }
                f = new Font(row.FontFamly, int.Parse(row.FontSize), row.Black ? FontStyle.Bold : FontStyle.Regular);
                s = new SolidBrush(row.Color);
                SizeF sizeF = g.MeasureString(text, f, (int)(row.Width / bl), format);



                if (Math.Ceiling(sizeF.Height) > relheight)
                {
                    relheight = (float)Math.Ceiling(sizeF.Height);
                }

            }
            double rowheight = 0;
            int left = 0;
            double temp1 = y;
            if (relheight > rowheight)
            {
                temp1 = temp1 + relheight - rowheight;
              
            }

            if (temp1 > Math.Floor((config.PageHeight - config.ItemHeight-config.Top-config.Bottom) / bl))
            {
                new_page = true;
                return;
            }

            foreach (KeyValuePair<string, SettingItem> item in config.Settings)
            {
                var row = item.Value;
                rowheight = Math.Ceiling(row.Height / bl);

                format.Alignment = getTextAlign(row.Align);
                format.LineAlignment = StringAlignment.Center;
                string text = ""; //row.Label;
                string[] names = row.Name.Split('/');
                for (int i = 0; i < names.Length; i++)
                {
                    if (data.Datafield.ContainsKey(names[i]))
                    {
                        var val = data.Datafield[names[i]];
                        for (int j = 0; j < row.Content.Count; j++)
                        {

                            int out_i = 0;
                            //val[row.Content[j].Name];
                            if (val.GetType().Name.Contains("List"))
                            {
                                List<Dictionary<string, string>> temp = (List<Dictionary<string, string>>)val;

                                if (!row.Content[j].Qiandao && int.TryParse(temp[0][row.Content[j].Name], out out_i))
                                {
                                    text += out_i.ToString();// data.Datafield.getKey(row.Name);
                                }
                                else
                                {
                                    text += temp[0][row.Content[j].Name];// data.Datafield.getKey(row.Name);

                                }

                            }
                            else
                            {
                                Dictionary<string, string> temp = (Dictionary<string, string>)val;
                                if (temp.ContainsKey(row.Content[j].Name))
                                {

                                    if (!row.Content[j].Qiandao && int.TryParse(temp[row.Content[j].Name], out out_i))
                                    {
                                        text += out_i.ToString();// data.Datafield.getKey(row.Name);
                                    }
                                    else
                                    {
                                        text += temp[row.Content[j].Name];// data.Datafield.getKey(row.Name);
                                    }

                                }
                            }

                            text += row.Content[j].Split;

                        }
                    }
                }
                f = new Font(row.FontFamly, int.Parse(row.FontSize), row.Black ? FontStyle.Bold : FontStyle.Regular);
                s = new SolidBrush(row.Color);
                Rectangle rect = new Rectangle((int)x + left, (int)y + (int)Math.Ceiling(row.Height / bl), (int)Math.Ceiling(row.Width / bl), (int)Math.Ceiling(relheight));

                g.DrawRectangle(pen,
                    (int)x + left,
                    (int)y + (int)Math.Ceiling(row.Height / bl),
                    (int)Math.Ceiling(row.Width / bl),
                    (int)relheight);
                g.DrawString(text, f, s, rect, format);//需要的参数

                left += (int)Math.Ceiling(row.Width / bl);

                _c++;
            }

            y = temp1;

        }

        private int _groupIndex = 0;
        private int _listIndex = 0;
        private int _pIndex = 0;
        private int _itemIndex = 0;
        ConfigCard card = new ConfigCard();
        private List<List<Dictionary<string, object>>> _cardPagelist = new List<List<Dictionary<string, object>>>();
        private int _recordIndex = 0;

        //(System.Drawing.Printing.PrintPageEventArgs e, drawItem drawItem)
        private void drawCard(System.Drawing.Printing.PrintPageEventArgs e)
        {
            Graphics g = e.Graphics;
            Font f = new Font("宋体", 10);
            SolidBrush s = new SolidBrush(Color.Black);

            StringFormat format = new StringFormat();
            //  format.LineAlignment = StringAlignment.Center;
            format.Alignment = StringAlignment.Far; //居中
            
            format.LineAlignment = StringAlignment.Center;
           
            int py = 0;
            int px = 0;
            Pen pen = new Pen(Color.Black);
            List<Dictionary<string, object>> page = new List<Dictionary<string, object>>();
            Dictionary<int, int> map = new Dictionary<int, int>();
            if (this._cardPagelist == null || this._cardPagelist.Count == 0)
            {
                List<List<Dictionary<string, object>>> pagelist = new List<List<Dictionary<string, object>>>();
                int recIndex = 0;

                record.ForEach(rec =>
                {
                    int cout = pagelist.Count;
                    // Record rec = record[0];
                    page = new List<Dictionary<string, object>>();
                    card.Childrens.ForEach(group =>
                    {
                        py = (int)(group.Top / bl);
                        px = (int)(group.Left / bl);
                        group.Childrens.ForEach(list =>
                        {
                            py += (int)(list.Top / bl);
                            px += (int)(list.Left / bl);
                            list.Childrens.ForEach(p =>
                            {
                                py += (int)(p.Top / bl);
                                px += (int)(p.Left / bl);
                                string text = ""; //data.getKey(item.Name); ;
                            PointF point = new PointF(px, py);
                                if (p.Indent > 0)
                                {
                                    for (int i = 0; i < p.Indent; i++)
                                    {
                                        text += " ";
                                    }
                                }
                                Dictionary<string, string> item1 = new Dictionary<string, string>();
                                p.Childrens.ForEach(item =>
                                {
                                    string datafield = item.Datafield;
                                    if (datafield == null)
                                    {
                                        datafield = p.Name;
                                    }
                                    if (datafield == null)
                                    {
                                        MessageBox.Show("请配置" + item.Label + "项的datafield或者其上级p节点的name");
                                        return;
                                    }
                                    if (rec.Datafield.ContainsKey(datafield))
                                    {
                                        var df = rec.Datafield[datafield];
                                        if (df.GetType().Name.Contains("List"))
                                        {
                                            List<Dictionary<string, string>> list1 = (List<Dictionary<string, string>>)df;

                                            if (datafield == "905" && item.Name == "b")
                                            {
                                                list1.ForEach(item2 =>
                                                {
                                                    if (item2.ContainsKey(item.Name))
                                                    {
                                                        text += item2[item.Name] + "\n"; // item.Label;
                                                    }
                                                });
                                            }
                                            else
                                            {
                                                item1 = list1[0];
                                                if (item1.ContainsKey(item.Name))
                                                {
                                                    text += item.Prev;
                                                    text += item1[item.Name]; // item.Label;
                                                    text += item.Next;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            item1 = ((Dictionary<string, string>)df);
                                            if (item1.ContainsKey(item.Name))
                                            {
                                                text += item.Prev;
                                                text += item1[item.Name]; // item.Label;
                                            text += item.Next;
                                            }
                                        }
                                    }

                                });

                                if (text.Trim().Length > 0)
                                {
                                    f = new Font(p.FontFamly, int.Parse(p.FontSize));
                                    format.Alignment = StringAlignment.Near;//getTextAlign(p.Align);
                                SizeF sizeF = g.MeasureString(text, f, (int)(group.Width / bl), format);
                                    Dictionary<string, object> drawp = new Dictionary<string, object>();

                                    drawp.Add("text", text);
                                    drawp.Add("f", f);
                                    drawp.Add("s", s);
                                    drawp.Add("format", format);
                                    Rectangle rect = new Rectangle(px, py, (int)(group.Width / bl), Convert.ToInt32(sizeF.Height));

                                //判断是否需要换页
                                if (py + Convert.ToInt32(sizeF.Height) > Convert.ToInt32(card.ItemHeight / bl))
                                    {
                                        Point point1 = new Point(Convert.ToInt32(card.ItemWidth / bl) - 100, Convert.ToInt32(card.ItemHeight / bl) - 15);
                                        Dictionary<string, object> drawp1 = new Dictionary<string, object>();
                                        drawp1.Add("text", "见次卡");
                                        drawp1.Add("f", f);
                                        drawp1.Add("s", s);
                                        drawp1.Add("point", point1);
                                        page.Add(drawp1);
                                        pagelist.Add(page);
                                        page = new List<Dictionary<string, object>>();
                                        px = Convert.ToInt32((card.Left + group.Left + list.Left + p.Left) / bl);
                                        py = Convert.ToInt32((card.Top + group.Top + list.Top + p.Top) / bl);
                                        rect = new Rectangle(px, py, (int)(group.Width / bl), Convert.ToInt32(sizeF.Height));
                                    }

                                    drawp.Add("rect", rect);

                                    page.Add(drawp);
                                // g.DrawString(text, f, s, rect, format);
                                px = (int)((group.Left + list.Left + p.Left) / bl);
                                    py += Convert.ToInt32(sizeF.Height);

                                // }
                            }

                            });
                        });


                    });
                    pagelist.Add(page);
                    if (pagelist.Count - cout > 1)
                    {
                        for (int i = cout; i < pagelist.Count; i++)
                        {
                            Point point = new Point(Convert.ToInt32(card.ItemWidth / bl) - 100, 0);
                            Dictionary<string, object> drawp = new Dictionary<string, object>();
                            drawp.Add("text", (i - cout + 1) + "/" + (pagelist.Count - cout));
                            drawp.Add("f", f);
                            drawp.Add("s", s);
                            drawp.Add("point", point);
                            pagelist[i].Add(drawp);
                        }
                    }
                });

                this._cardPagelist = pagelist;
            }

            page = this._cardPagelist[this._curPageIndex];

            page.ForEach(item =>
            {
                if (item.Count == 5)
                {
                    g.DrawString(item["text"].ToString(), (Font)(item["f"]), (SolidBrush)item["s"], (Rectangle)item["rect"], (StringFormat)item["format"]);
                }
                else
                {
                    g.DrawString(item["text"].ToString(), (Font)(item["f"]), (SolidBrush)item["s"], (Point)item["point"]);

                }
            });
            
            //if (this._cardPagelist.Count > 1)
            //{
            //    Point point = new Point(Convert.ToInt32(card.ItemWidth / bl)-100, 0);
            //    g.DrawString((this._curPageIndex+1)+"/"+ (this._cardPagelist.Count), f,s,point);

            //}
            
            if (this._curPageIndex < this._cardPagelist.Count - 1)
            {
                //Point point = new Point(Convert.ToInt32(card.ItemWidth / bl) - 100, Convert.ToInt32(card.ItemHeight / bl)-15);
                //g.DrawString("见次卡", f, s, point);
                this._curPageIndex++;
                e.HasMorePages = true;
                printPreviewControl.Rows++;

            }
            else
            {
                e.HasMorePages = false;
            }
        }
        private void drawCard(Graphics g, double x, double y)
        {

            Font f = new Font("黑体", 18);
            SolidBrush s = new SolidBrush(Color.Black);
           
            StringFormat format = new StringFormat();
            //  format.LineAlignment = StringAlignment.Center;
            format.Alignment = StringAlignment.Far; //居中

            ConfigCard card = new ConfigCard();
         
                format.LineAlignment = StringAlignment.Center;
            int piany = 10 ;
            int pianx = 200;
            int py = 0;
            int px = pianx;
            Pen pen = new Pen(Color.Black);

            if (this._cardPagelist == null || this._cardPagelist.Count == 0)
            {


                List<List<Dictionary<string, object>>> pagelist = new List<List<Dictionary<string, object>>>();
                List<Dictionary<string, object>> page = new List<Dictionary<string, object>>();
                card.Childrens.ForEach(group =>
                    {
                        py = (int)(group.Top / bl);
                        px = (int)(group.Left / bl);
                        group.Childrens.ForEach(list =>
                        {

                            py += (int)(group.Top / bl);
                            px += (int)(list.Left / bl);
                            list.Childrens.ForEach(p =>
                            {
                                py += (int)(p.Top / bl);
                                px += (int)(p.Left / bl);
                                string text = ""; //data.getKey(item.Name); ;
                            PointF point = new PointF(px, py);
                                if (p.Indent > 0)
                                {
                                    for (int i = 0; i < p.Indent; i++)
                                    {
                                        text += " ";
                                    }
                                }
                                Dictionary<string, string> item1 = new Dictionary<string, string>();



                                p.Childrens.ForEach(item =>
                                {
                                    string datafield = item.Datafield;
                                    if (datafield == null)
                                    {
                                        datafield = p.Name;
                                    }
                                    if (datafield == null)
                                    {
                                        MessageBox.Show("请配置" + item.Label + "项的datafield或者其上级p节点的name");
                                        return;
                                    }
                                    if (record[0].Datafield.ContainsKey(datafield))
                                    {
                                        var df = record[0].Datafield[datafield];
                                        if (df.GetType().Name.Contains("List"))
                                        {

                                            List<Dictionary<string, string>> list1 = (List<Dictionary<string, string>>)df;
                                            item1 = list1[0];

                                        //list1.ForEach(item1 =>
                                        //{
                                        //    text = "";
                                        //    p.Childrens.ForEach(item =>
                                        //    {
                                        //        text += item1[item.Name]; // item.Label;

                                        //    });
                                        //    f = new Font(p.FontFamly, int.Parse(p.FontSize));
                                        //    format.Alignment = StringAlignment.Center;
                                        //    SizeF sizeF = g.MeasureString(text, f, (int)(group.Width / bl), format);

                                        //    point = new PointF(px, py);
                                        //    Rectangle rect = new Rectangle(px, py, (int)(group.Width / bl), Convert.ToInt32(sizeF.Height));

                                        //    g.DrawRectangle(pen, px, py, (int)(group.Width / bl), Convert.ToInt32(sizeF.Height));

                                        //    g.DrawString(text, f, s, rect, format);
                                        //    px = (int)((group.Left + list.Left + p.Left) / bl);
                                        //    py += Convert.ToInt32(sizeF.Height);
                                        //});
                                    }
                                        else
                                        {
                                        //item1 = ((DataField)df).Subfield;

                                        item1 = ((Dictionary<string, string>)df);
                                        }
                                        if (item1.ContainsKey(item.Name))
                                        {
                                            text += item.Prev;
                                            text += item1[item.Name]; // item.Label;
                                        text += item.Next;
                                        }
                                    }

                                });

                                if (text.Trim().Length > 0)
                                {
                                    f = new Font(p.FontFamly, int.Parse(p.FontSize));
                                    format.Alignment = StringAlignment.Near;//getTextAlign(p.Align);
                                SizeF sizeF = g.MeasureString(text, f, (int)(group.Width / bl), format);
                                    Dictionary<string, object> drawp = new Dictionary<string, object>();

                                    drawp.Add("text", text);
                                    drawp.Add("f", f);
                                    drawp.Add("s", s);
                                    drawp.Add("format", format);
                                    Rectangle rect = new Rectangle(px, py, (int)(group.Width / bl), Convert.ToInt32(sizeF.Height));

                                //判断是否需要换页
                                if (py + Convert.ToInt32(sizeF.Height) > Convert.ToInt32(card.ItemHeight / bl))
                                    {
                                        pagelist.Add(page);
                                        page = new List<Dictionary<string, object>>();
                                        px = Convert.ToInt32((card.Left + group.Left + list.Left + p.Left) / bl);
                                        py = Convert.ToInt32((card.Top + group.Top + list.Top + p.Top) / bl);
                                        rect = new Rectangle(px, py, (int)(group.Width / bl), Convert.ToInt32(sizeF.Height));
                                    }



                                    drawp.Add("rect", rect);

                                // point = new PointF(px, py);

                                //g.DrawRectangle(pen, px, py, (int)(group.Width / bl), Convert.ToInt32(sizeF.Height));

                                page.Add(drawp);
                                // g.DrawString(text, f, s, rect, format);
                                px = (int)((group.Left + list.Left + p.Left) / bl);
                                    py += Convert.ToInt32(sizeF.Height);

                                // }
                            }

                            });
                        });
                    });

            }
            else
            {
                List<Dictionary<string, object>> page = this._cardPagelist[this._curPageIndex];

                List<List<Dictionary<string, object>>> pagelist = this._cardPagelist;
                page.ForEach(item =>
                {
                    
                    g.DrawString(item["text"].ToString(), (Font) (item["f"]),( SolidBrush)item["s"], (Rectangle)item["rect"],(StringFormat) item["format"]);

                });

                if (this._curPageIndex < this._cardPagelist.Count)
                {
                    this._curPageIndex++;

                }

            }
        }
        const double millimererTopixel = 25.4;

       
        private StringAlignment getTextAlign(string align)
        {
            switch (align) {
                case "left":
                    return StringAlignment.Near;
                case "center":
                    return StringAlignment.Center;
                case "right":
                    return StringAlignment.Far;
            }

            return StringAlignment.Center;

        }

        private void creatLabelDemo()
        {
            panel1.Height = (int)Math.Floor(config.ItemHeight / bl);

            if (printTypeView.SelectedNode != null && printTypeView.SelectedNode.Text == "财产帐报表")
            {
                panel1.Height = (int)Math.Floor(config.ItemHeight * 3 / bl);

            }
            panel1.Width = (int)Math.Floor(config.ItemWidth / bl);
            panel1.Controls.Clear();
            if (listLbl.SelectedValue == null)
                return;
            if (listLbl.SelectedValue.ToString() != "反面反面")
            {
                foreach (KeyValuePair<string, SettingItem> item in config.Settings)
                {
                    var row = item.Value;
                    if (row == null || row.IsHide || (row.Label != null && row.Label.Contains("反面")))
                    {
                        continue;
                    }
                    Label label = new Label();

                    label.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

                    if (listLbl.SelectedValue != null && row.Name + row.Label == listLbl.SelectedValue.ToString())
                    {
                        label.BackColor = Color.Orange;
                    }
                    else
                    {
                        label.BackColor = Color.Transparent;
                    }

                    label.TextAlign = ContentAlignment.MiddleCenter;// row[0].Align;

                    label.Font = new Font(row.FontFamly, int.Parse(row.FontSize), row.Black ? FontStyle.Bold : FontStyle.Regular);
                    label.ForeColor = row.Color;
                    label.Text += row.Label + "" + row.Name;

                    if (row.Name == "img")
                    {
                        PictureBox pb = new PictureBox();

                        pb.Location = new System.Drawing.Point((int)Math.Floor(row.Left / bl), (int)Math.Floor(row.Top / bl));
                        pb.Size = new System.Drawing.Size((int)Math.Floor(row.Width / bl), (int)Math.Floor(row.Height / bl));

                        panel1.Controls.Add(pb);

                    }
                    else
                    {
                        label.Location = new System.Drawing.Point((int)Math.Floor(row.Left / bl), (int)Math.Floor(row.Top / bl));

                        label.Size = new System.Drawing.Size((int)Math.Floor(row.Width / bl), (int)Math.Floor(row.Height / bl));
                        panel1.Controls.Add(label);

                    }

                }

            }
            else

               if (config.Settings.ContainsKey(listLbl.SelectedValue.ToString()))
            {

                var rowItem = config.Settings.First(source =>
                   {
                       return source.Key == listLbl.SelectedValue.ToString();
                   });
                if (rowItem.Key != null)
                {
                    var row = rowItem.Value;
                    RichTextBox tb = new RichTextBox();
                    tb.Text = row.ItemContent;
                    tb.TextChanged += Tb_TextChanged;
                    tb.Size = new System.Drawing.Size((int)Math.Floor(row.Width / bl), (int)Math.Floor(row.Height / bl));
                    tb.Location = new System.Drawing.Point((int)Math.Floor(row.Left / bl), (int)Math.Floor(row.Top / bl));

                    panel1.Controls.Add(tb);
                }
            }


        }

        private void Tb_TextChanged(object sender, EventArgs e)
        {
            setting_Changed("content", ((RichTextBox)sender).Text);

        }


        private void setPage(string pageType,int width,int height)
        {
            PaperSize p = new PaperSize("Custom", (int)Math.Round(width / bl), (int)Math.Round(height / bl));
            // PaperSize p = new PaperSize("Custom", (int)Math.Round(125 / bl), (int)Math.Round(225 / bl));


            this.printDocument.DefaultPageSettings.PaperSize = p;
            printPreviewControl1.InvalidatePreview();
        }

        private void pageType_SelectedIndexChanged(object sender, EventArgs e)
        {
            string pageType = this.pageType.SelectedItem.ToString();
            int width = int.Parse(this.txtWidth.Text);
            int height = int.Parse(this.txtHeight.Text);
            PaperSize p = null;

            if (pageType == "自定义")
            {
                txtHeight.Enabled = true;
                txtWidth.Enabled = true;
                p = new PaperSize("Custom", (int)Math.Round(width / bl), (int)Math.Round(height / bl));
            }
            else
            {
                txtHeight.Enabled =false;
                txtWidth.Enabled = false;
                foreach (PaperSize ps in this.printDocument.PrinterSettings.PaperSizes)
                {
                    if (ps.PaperName.Equals(pageType))
                    {
                        this.txtHeight.Text = (Math.Round(ps.Height * bl)).ToString();
                        this.txtWidth.Text = (Math.Round(ps.Width * bl)).ToString();
                        p = ps;
                    }
                }
            }
            setting_Changed("txtPageWidth");
            setting_Changed("txtPageHeight");
            this.printDocument.DefaultPageSettings.PaperSize = p;
            printPreviewControl.InvalidatePreview();
            printPreviewControl1.InvalidatePreview();
        }

       
        private void isTransverse_CheckedChanged(object sender, EventArgs e)
        {
           // this.printDocument.DefaultPageSettings.Landscape = isTransverse.Checked;
            //printPreviewControl1.Document.DefaultPageSettings.Landscape= isTransverse.Checked;
            //printPreviewControl.Document.DefaultPageSettings.Landscape = isTransverse.Checked;
            PaperSize p = new PaperSize("Custom", (int)Math.Round(config.PageWidth / bl), (int)Math.Round(config.PageHeight / bl));

            this.printDocument.DefaultPageSettings.PaperSize = p;

            printPreviewControl1.InvalidatePreview();
            printPreviewControl.InvalidatePreview();

            config.IsTransverse = isTransverse.Checked;

            if (isTransverse.Checked)
            {
                int out_put = 0;
                if (int.TryParse(txtWidth.Text, out out_put))
                {
                    config.PageHeight = out_put;
                }
                if (int.TryParse(txtHeight.Text, out out_put))
                {
                    config.PageWidth = out_put;
                }
            }
            else
            {
                int out_put = 0;
                if (int.TryParse(txtWidth.Text, out out_put))
                {
                    config.PageWidth = out_put;
                }
                if (int.TryParse(txtHeight.Text, out out_put))
                {
                    config.PageHeight = out_put;
                }
            }
        }

        private void listLbl_SelectedIndexChanged(object sender, EventArgs e)
        {

            string key = listLbl.SelectedValue.ToString(); //+((DataRowView)listLbl.SelectedItem)["Text"];
            if (key == "905e")
            {
                ckbQiandao.Show();
            }
            else
            {
                ckbQiandao.Hide();
            }
            if (config.Settings.ContainsKey(key))
            {
                SettingItem item = config.Settings[key];
                //txtColNum.Text = item.ColNum;
                //txtRowNum.Text = item.RowNum;
                txtFontFamly.Text = item.FontFamly;
                txtFontSize.Text = item.FontSize;
                cbxAlign.SelectedValue = item.Align;
                ckbBlack.Checked = item.Black;
                ckbQiandao.Checked = item.Qiandao;
                txtColHeight.Text = item.Height.ToString();
                txtcolWidth.Text = item.Width.ToString();
                txtcolTop.Text = item.Top.ToString();
                txtcolLeft.Text = item.Left.ToString();
                cbxisHidden.Checked = item.IsHide;

                if (item.Label != null)
                {
                    txtLabel.Text = item.Label.ToString();
                }
                cbxAlign.SelectedValue = item.Align;
                txtSplit.Text = item.Split;
                button2.BackColor = item.Color;
            }

          
        }

        private void txtRowNum_TextChanged(object sender, EventArgs e)
        {
            setting_Changed("txtRowNum");
        }

        private void setting_Changed(string name)
        {
            float oval = 0;
            int out_i = 0;
            if (name== "txtLblHeight"&& float.TryParse(txtLblHeight.Text,out oval))
            {
                config.ItemHeight = oval;
            }else if(name == "txtLblWidth" && float.TryParse(txtLblWidth.Text, out oval))
            {
                config.ItemWidth = oval;
            }
            if (name == "txtPageHeight" && int.TryParse(txtHeight.Text, out out_i))
            {
                config.PageHeight = out_i;
            }
            else if (name == "txtPageWidth" && int.TryParse(txtWidth.Text, out out_i))
            {
                config.PageWidth = out_i;
            }

            if (listLbl.SelectedValue != null&&config.Settings.ContainsKey(listLbl.SelectedValue.ToString()))
            {
               
                //if(name== "txtColNum")
                //config.Settings[listLbl.SelectedItem.ToString()].ColNum = txtColNum.Text;
                //if (name == "txtRowNum")
                //    config.Settings[listLbl.SelectedItem.ToString()].RowNum = txtRowNum.Text;
                if (name == "txtFontFamly")

                    config.Settings[listLbl.SelectedValue.ToString()].FontFamly = txtFontFamly.Text;
                if (name == "txtFontSize" && float.TryParse(txtcolWidth.Text, out oval))
                    config.Settings[listLbl.SelectedValue.ToString()].FontSize = txtFontSize.Text;
                if (name == "ckbBlack")

                    config.Settings[listLbl.SelectedValue.ToString()].Black = ckbBlack.Checked;
                if (name == "ckbQiandao")
                    config.Settings[listLbl.SelectedValue.ToString()].Qiandao = ckbQiandao.Checked;
                if (name == "txtColHeight" && float.TryParse(txtColHeight.Text, out oval))

                    config.Settings[listLbl.SelectedValue.ToString()].Height = oval;
                if (name == "txtcolWidth"&& float.TryParse(txtcolWidth.Text,out oval))
                      config.Settings[listLbl.SelectedValue.ToString()].Width = float.Parse(txtcolWidth.Text);
                if (name == "txtcolTop" && float.TryParse(txtcolTop.Text, out oval))
                    config.Settings[listLbl.SelectedValue.ToString()].Top = float.Parse(txtcolTop.Text);
                if (name == "txtcolLeft" && float.TryParse(txtcolLeft.Text, out oval))
                    config.Settings[listLbl.SelectedValue.ToString()].Left = float.Parse(txtcolLeft.Text);
                if (name == "txtLabel" )
                    config.Settings[listLbl.SelectedValue.ToString()].Label = txtLabel.Text;
                if (name == "txtSplit")
                    config.Settings[listLbl.SelectedValue.ToString()].Split = txtSplit.Text;
                if (name == "isHidden")
                    config.Settings[listLbl.SelectedValue.ToString()].IsHide =cbxisHidden.Checked;
                if (name == "text_align")
                    config.Settings[listLbl.SelectedValue.ToString()].Align = cbxAlign.SelectedValue.ToString();
                if (name == "color")
                    config.Settings[listLbl.SelectedValue.ToString()].Color = button2.BackColor;
                if (name == "qiandao")
                    config.Settings[listLbl.SelectedValue.ToString()].Qiandao =ckbQiandao.Checked;
               


            }
            creatLabelDemo();
        }
        private void setting_Changed(string name,string value)
        {
           
            if (listLbl.SelectedValue != null && config.Settings.ContainsKey(listLbl.SelectedValue.ToString()))
            {

              
                if (name == "content")
                    config.Settings[listLbl.SelectedValue.ToString()].ItemContent = value;
               
            }
         
        }

        private void txtLblWidth_TextChanged(object sender, EventArgs e)
        {
            panel1.Width = (int)Math.Floor(int.Parse(txtLblWidth.Text) / 0.254);
            setting_Changed("txtLblWidth");
        }


        private void txtLblHeight_TextChanged(object sender, EventArgs e)
        {
            panel1.Height = (int)Math.Floor(int.Parse(txtLblHeight.Text) / 0.254);
            setting_Changed("txtLblHeight");

        }

    
      
        private void button1_Click(object sender, EventArgs e)
        {
            config.save();
        }

       

        private void tab_control_SelectedIndexChanged(object sender, EventArgs e)
        {
          if(tab_control.SelectedIndex == 3)
            {
                printPreviewControl.InvalidatePreview();

            }
        }

        private void txtFontFamly_TextChanged(object sender, EventArgs e)
        {
            setting_Changed("txtFontFamly");
        }

        private void txtFontSize_TextChanged(object sender, EventArgs e)
        {
            setting_Changed("txtFontSize");

        }

        private void txtLabel_TextChanged(object sender, EventArgs e)
        {
            setting_Changed("txtLabel");
        }

        OpenFileDialog openFileDialog = new OpenFileDialog();
        private void button2_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
               // image = Image.FromFile(openFileDialog.FileName);
                creatLabelDemo();
            }
        }

        private void printTypeView_Click(object sender, EventArgs e)
        {
            string name = "";
            if (printTypeView.SelectedNode.Text=="标签打印")
            {
                config = new Config("label");
                name = "label";
            }
            if (printTypeView.SelectedNode.Text == "读者证打印")
            {
                config = new Config("reader");
                name = "reader";

            }
            if (printTypeView.SelectedNode.Text == "财产帐报表")
            {
                name = "report";
                config = new Config("report");
            }
            if (printTypeView.SelectedNode.Text == "卡片打印")
            {
                name = "card";
                
            }
            form_init(name);
        }

        private void printDocument_EndPrint(object sender, PrintEventArgs e)
        {
             this._curPageIndex = 0;
            this._totalPage = 1;
            this._pageIndex = 0;
            this._pageSize = 1;
            this._fromPage = -1;
            this._toPage = -1;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            DataTable dataTable = new DataTable();

            dataTable.Columns.Add("第一列");
            dataTable.Columns.Add("第二列");

            dataTable.Columns.Add("第三列");
            dataTable.Columns.Add("第四列");
            dataTable.Columns.Add("第5列");

            for(int i = 0; i < 100; i++)
            {
                DataRow dr = dataTable.NewRow();
                dr[0] = "第"+i+"行第一列";
                dr[1] = "第" + i + "行第二列";
                dr[2] = "第" + i + "行第三列";
                dr[3] = "第" + i + "行第四列";
                dr[4] = "第" + i + "行第5列";


                dataTable.Rows.Add(dr);


            }

            new PrintHelper().PrintPriview(dataTable, "测试打印");
        }

        private void button4_Click(object sender, EventArgs e)
        {

            new PrintLabelHelper().PrintPriview(readerData, "测试打印");

            return;
                try
                {
                    var printPriview = new PrintPreviewDialog
                    {
                        Document = printDocument,
                        WindowState = FormWindowState.Maximized
                    };
                    printPriview.ShowDialog();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("打印错误，请检查打印设置！");
                }
            
        }

        private void printDocument_BeginPrint(object sender, PrintEventArgs e)
        {
            this.initPrint();

        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            PrintDialog printDialog = new PrintDialog();
            printDialog.AllowSomePages = true;
            printDialog.PrinterSettings.FromPage =0;
            printDialog.PrinterSettings.DefaultPageSettings.PrinterSettings = printDocument.DefaultPageSettings.PrinterSettings;
            printDialog.PrinterSettings.ToPage = 10;
            printDialog.PrinterSettings.MinimumPage = 1;
            printDialog.PrinterSettings.MaximumPage = 10;
            printDialog.Document = printDocument;
            printDialog.UseEXDialog = true;
            PageSetupDialog pd = new PageSetupDialog();
            pd.Document = printDocument;

            DialogResult result = printDialog.ShowDialog();

            // DialogResult result =printDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                //this._fromPage = printDialog.PrinterSettings.FromPage;
                //this._toPage = printDialog.PrinterSettings.ToPage;


                // MessageBox.Show("printDialogheight:"
                //+ printDialog.PrinterSettings.DefaultPageSettings.PaperSize.Height
                //+ ",printDialogwidth:" + printDialog.PrinterSettings.DefaultPageSettings.PaperSize.Width
                //+ "printDocumentheight:"
                //+ printDocument.PrinterSettings.DefaultPageSettings.PaperSize.Height
                //+ ",printDocumentwidth:" + printDocument.PrinterSettings.DefaultPageSettings.PaperSize.Width);

          //      MessageBox.Show("FromPage:"
          //  + printDialog.PrinterSettings.FromPage
          //  + ",ToPage:" + printDialog.PrinterSettings.ToPage
          //);
                try
                {
                    if (printDialog.PrinterSettings.PrintRange == PrintRange.SomePages) //在此处判断,是否选择了"页"选项,还是"全部"
                    {
                        //page = this.printDialog.PrinterSettings.FromPage;
                        //maxpage = this.printDialog.PrinterSettings.ToPage;
                        //b = page - 1;  //用在函数 PrintPage 中
                        //d = maxpage;    //用在函数 PrintPage 中
                    }
                    else
                    {
                      //  page = 0;     //用在函数 PrintPage 中
                      //  maxpage = c - 1;   //用在函数 PrintPage 中
                    }
                  //  printDocument.PrintPage -= new PrintPageEventHandler(zdy);   //form_load中有调用此函数,此命令中不要执行此函数
                    //printDocument.PrintPage -= new PrintPageEventHandler(printDocument_PrintPage);   //预览文件多次打印,作用是清空归零原内容
                    //printDocument.PrintPage += new PrintPageEventHandler(printDocument_PrintPage);
                   printDialog.Document.Print();
                }
                catch
                {
                    MessageBox.Show("无法连接打印机");
                    return;
                }
            }
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            try
            {
                var printPriview = new PrintPreviewDialog
                {
                    Document = printDocument,
                    WindowState = FormWindowState.Maximized
                };
                printPriview.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show("打印错误，请检查打印设置！");
            }
        }

        private void main_form_Load(object sender, EventArgs e)
        {

        }

        private void txtItemLeft_TextChanged(object sender, EventArgs e)
        {
            int out_put = 0;
            int.TryParse(txtItemLeft.Text, out out_put);
            config.Left = out_put;
        }

        private void txtItemTop_TextChanged(object sender, EventArgs e)
        {
            int out_put = 0;
            int.TryParse(txtItemTop.Text, out out_put);
            config.Top = out_put;
        }

        private void toolStripTextBox1_Click(object sender, EventArgs e)
        {
            printPreviewControl.Columns = 2;
        }

        private void txtWidth_TextChanged(object sender, EventArgs e)
        {
            PaperSize p = null;

            if (this.pageType.SelectedItem != null && this.pageType.SelectedItem.ToString() == "自定义")
            {
                txtHeight.Enabled = Enabled;
                txtWidth.Enabled = Enabled;

                int out_put = 0;
                if (int.TryParse(txtHeight.Text, out out_put))
                    config.PageHeight = out_put;
                if (int.TryParse(txtWidth.Text, out out_put))
                    config.PageWidth = out_put;
                p = new PaperSize("Custum", (int)Math.Round(config.PageWidth / bl), (int)Math.Round(config.PageHeight / bl));
                this.printDocument.DefaultPageSettings.PaperSize = p;
                printPreviewControl1.InvalidatePreview();
                printPreviewControl.InvalidatePreview();
            }

            setting_Changed("txtPageWidth");
            setting_Changed("txtPageHeight");

        }

        private void txtcolLeft_ValueChanged(object sender, EventArgs e)
        {
            setting_Changed("txtcolLeft");

        }

        private void txtcolWidth_ValueChanged(object sender, EventArgs e)
        {
            setting_Changed("txtcolWidth");

        }

        private void txtColHeight_ValueChanged(object sender, EventArgs e)
        {
            setting_Changed("txtColHeight");

        }

        private void txtcolTop_ValueChanged(object sender, EventArgs e)
        {
            setting_Changed("txtcolTop");

        }

        private void txtSplit_TextChanged(object sender, EventArgs e)
        {
            setting_Changed("txtSplit");
        }

        private void cbxisHidden_CheckedChanged(object sender, EventArgs e)
        {
            setting_Changed("isHidden");

        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (config.Settings.ContainsKey(listLbl.SelectedValue.ToString()))
            {
                SettingItem item = config.Settings[listLbl.SelectedValue.ToString()];
                //txtColNum.Text = item.ColNum;
                //txtRowNum.Text = item.RowNum;
                txtFontFamly.Text = item.FontFamly;
                txtFontSize.Text = item.FontSize;
                cbxAlign.SelectedValue = item.Align;

                ckbBlack.Checked = item.Black;
                ckbQiandao.Checked = item.Qiandao;
                txtColHeight.Text = item.Height.ToString();
                txtcolWidth.Text = item.Width.ToString();
                txtcolTop.Text = item.Top.ToString();
                txtcolLeft.Text = item.Left.ToString();
                cbxisHidden.Checked = item.IsHide;
                if (item.Label != null)
                {
                    txtLabel.Text = item.Label.ToString();
                }
                cbxAlign.SelectedValue = item.Align;
                txtSplit.Text = item.Split;

            }
        }

        private void cbxAlign_SelectedIndexChanged(object sender, EventArgs e)
        {
            setting_Changed("text_align");

        }

        private void tabPrintSetting_Click(object sender, EventArgs e)
        {

        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            ColorDialog dialog = new ColorDialog();
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                Color GetColor = dialog.Color;
                //GetColor就是用户选择的颜色，接下来就可以使用该颜色了
                button2.BackColor = GetColor;

                setting_Changed("color");
            }
        }
        private void button3_Click_1(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {

                //PictureBox控件显示图片
                pbhuibiao.Load(openFileDialog.FileName);
            }
        }
        
        private void printTypeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            string name = "";
            if (printTypeView.SelectedNode.Text == "标签打印")
            {
                config = new Config("label");
                name = "label";

            }
            if (printTypeView.SelectedNode.Text == "读者证打印")
            {
                config = new Config("reader");
                name = "reader";
            }
            if (printTypeView.SelectedNode.Text == "财产帐报表")
            {
                name = "report";
                config = new Config("report");
            }
            if (printTypeView.SelectedNode.Text == "卡片打印")
            {
                name = "card";
            }
            form_init(name);
        }

        private void ckbQiandao_CheckedChanged(object sender, EventArgs e)
        {
            setting_Changed("qiandao");

        }

        private void ckbBlack_CheckedChanged(object sender, EventArgs e)
        {
            setting_Changed("ckbBlack");

        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            dialog.Description = "请选择Txt所在文件夹";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (string.IsNullOrEmpty(dialog.SelectedPath))
                {
                   MessageBox.Show(this, "文件夹路径不能为空", "提示");
                    return;
                }
                else
                {
                    label10.Text = dialog.SelectedPath;
                }
              
            }
        }

        private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
           
        }

        private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            int index = e.Index;
            if (ckbchektype.CheckedItems.Count > 0)
            {
                for (int i = 0; i < ckbchektype.Items.Count; i++)
                {
                    if (i != index)
                    {
                        ckbchektype.SetItemCheckState(i, System.Windows.Forms.CheckState.Unchecked);
                    }
                }
            }
        }

        private void txtStart_TextChanged(object sender, EventArgs e)
        {
            int out_start = 0;
            if (int.TryParse(txtStart.Text,out out_start))
            {
                config.Start = out_start;
            }

        }

        private void cmbsort_SelectedIndexChanged(object sender, EventArgs e)
        {
            config.SortBy = cmbsort.Text!="录入时间"?"905b":"905w";

        }

        private void txtItemRight_TextChanged(object sender, EventArgs e)
        {
            int out_put = 0;
            int.TryParse(txtItemRight.Text, out out_put);
            config.Right = out_put;
        }

        private void txtItemBottom_TextChanged(object sender, EventArgs e)
        {
            int out_put = 0;
            int.TryParse(txtItemBottom.Text, out out_put);
            config.Bottom = out_put;
        }
    }
}
